package com.iman.locker.service;

import android.app.Notification;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.iman.locker.manager.ILockerManager;
import com.iman.locker.manager.LockerManager;
import com.iman.locker.view.LockActivity;


/**
 * 看门狗服务(负责监测应用的启动情况）
 * Created by esirong on 2015/11/19.
 */
public class WatchDogService extends Service {

    private static final String TAG = "WatchDogService";
    public static final int FOREGROUND_ID = 1;//设置id=0可以不显示在通知栏中。
    private ILockerManager lockerManager;//锁管理
    private AppsWatcher mLaunchWatcher;//应用启动要查看器
    InnerReceiver innerBroadcastReceiver;

    //应用启动监听

    /**
     * 启动看门狗（开始工作吧）
     *
     * @param context 上下文
     */
    public static void start(Context context) {
        Intent serviceIntent = new Intent(context, WatchDogService.class);
        context.startService(serviceIntent);
    }

    //应用启动监听
    private final AppsWatcher.OnAppLauncherListener appLauncherListener = new AppsWatcher.OnAppLauncherListener() {
        @Override
        public void onAppLaunched(String appPackageName) {
            performAppCheck(appPackageName);
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //这个设置可以使用本服务的位于最靠近前台，增强存活
        startForeground(FOREGROUND_ID, new Notification());
        mLaunchWatcher = new AppsWatcher(this);
        mLaunchWatcher.addAppLauncherListener(appLauncherListener);
        lockerManager = new LockerManager();
        //采用代码方式注册广播接收者
        registerInnerReceiver();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //手动返回START_STICKY。当设备内存充足时，此服务可被尝试唤醒（此前因内存紧用被回收的时）
        flags = START_STICKY;

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Intent service = new Intent(this, WatchDogService.class);
        this.startService(service);
        stopForeground(true);
        unRegisterInnerReceiver();
        super.onDestroy();
    }

    /**
     * 检查启动的APP
     */
    public void performAppCheck(String appPackageName) {
        Log.e(TAG, "应用启动：" + appPackageName);
        if (isNeedLock()) {
            Log.e(TAG, "锁定：" + appPackageName);
            lockApp(appPackageName);
        }

    }

    /**
     * 检查是不是需要加锁（如果当前锁的类型设定了密码）
     *
     * @return 如果当前锁的类型设定了密码则返回true
     */
    private boolean isNeedLock() {
        boolean showLockerView = lockerManager.isInitPassword();
        return showLockerView;
    }

    /**
     * 锁定
     */
    public void lockApp(String appPackageName) {
        LockActivity.showLocker(this, appPackageName);
        mLaunchWatcher.stopCheckApp(appPackageName);
    }

    //检查锁的类型
    private int checkLockerType() {
        int result = -1;


        return result;

    }

    private void registerInnerReceiver() {

        innerBroadcastReceiver = new InnerReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        registerReceiver(innerBroadcastReceiver, filter);
    }

    private void unRegisterInnerReceiver() {
        unregisterReceiver(innerBroadcastReceiver);
    }

    private class InnerReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                mLaunchWatcher.start();
            }
            if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                mLaunchWatcher.stop();
            }
        }

    }
}
